package flexconsole.utils {
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	/**
	 * Utility for File related operations.
	 *
	 * @author ivanchoo
	 *
	 */
	public class FileUtil {
		
		static private var logger:ILogger = Log.getLogger("flexconsole.utils.FileUtil");
		
		/**
		 * Reads the content for a file.
		 *
		 * @param file
		 * @return
		 *
		 */
		static public function readFile(file:File):String {
			var str:String;
			
			try {
				if (file.exists && !file.isDirectory && !file.isPackage) {
					var io:FileStream = new FileStream();
					io.open(file, FileMode.READ);
					str = String(io.readUTFBytes(io.bytesAvailable));
					io.close();
				}
			} catch (e:Error) {
				logger.error(e.message);
			}
			return str;
		}
		
		/**
		 * Writes content to file.
		 *
		 * @param file
		 * @param str
		 * @return
		 *
		 */
		static public function writeFile(file:File, str:String):Boolean {
			if (file.exists && (file.isDirectory || file.isPackage)) {
				return false;
			}
			
			try {
				if (!str) {
					str = '';
				} else {
					str = str.replace(/\n/g, File.lineEnding);
				}
				var io:FileStream = new FileStream();
				io.open(file, FileMode.WRITE);
				io.writeUTFBytes(str);
				io.close();
				return true;
			} catch (e:Error) {
				logger.error(e.message);
			}
			return false;
		}
		
		/**
		 * Reads content of a file as XML.
		 *
		 * @param file
		 * @return
		 *
		 */
		static public function readFileAsXML(file:File):XML {
			var str:String = readFile(file);
			return str ? new XML(str) : null;
		}
		
		/**
		 * Writes content of a file as XML.
		 *
		 * @param file
		 * @param xml
		 * @return
		 *
		 */
		static public function writeFileAsXML(file:File, xml:XML):Boolean {
			var str:String = '<?xml version="1.0" encoding="utf-8"?>\n';
			str += xml.toXMLString();
			return writeFile(file, str);
		}
		
		/**
		 * Create a file object where the path actually exists based on the given path fallback options.
		 *
		 * <p>This method is guaranteed to return a <code>File</code> object where the directory exists.
		 * If none of the given path options exists, the <code>File.documentsDirectory</code> is returned</p>
		 * @param
		 * @param rest
		 *
		 */
		static public function createFileThatExistsSafely(... rest):File {
			var file:File;
			var path:String;
			
			while (rest.length) {
				path = rest.shift() as String;
				
				if (path && path.length) {
					try {
						file = new File(path);
						
						if (!file.exists) {
							file = null;
							continue;
						} else {
							break;
						}
					} catch (e:Error) {
						//	ignore
					}
				}
			}
			
			if (!file) {
				file = File.documentsDirectory.clone();
			}
			return file;
		}
		
		public function FileUtil() {
		}
	
	}
}